package rabid;

import java.util.HashMap;
import java.util.Vector;


public class Query {
	
	Vector Results;
	int fileWeight[];
	int similar[];
	
	String[] files;
	
	public Query(String[]queryTerms, HashMap corpusWords, String[] corpusFiles, int numFiles){
		Results = new Vector();	
		fileWeight = new int[numFiles];
		similar = new int[numFiles];
				
		setFileWeight(queryTerms,corpusWords);
		setResults();
		
		files = new String[Results.size()];
		
		for(int i=0;i<Results.size();i++){
			files[i] = corpusFiles[((Integer)Results.get(i)).intValue()]; 
		}
	}
	
	private void setFileWeight(String[]queryTerms, HashMap corpusWords){
		int i,x;
		int[] counts;
		for(i=0;i<queryTerms.length;i++){			
			counts = (int[])corpusWords.get(queryTerms[i]);
			if(counts != null){
				for(x=0;x<counts.length;x++){
					if(counts[x] > 0){
						fileWeight[x] += counts[x];
						similar[x]++;
					}
				}
			}
		}
		
		for(i=0;i<similar.length;i++){
			if(similar[i] < queryTerms.length)
				fileWeight[i] = 0;
		}
	}//end setFileWeight()
	
	private void setResults(){
		int currIndex=0;
		int currResult=0;
		int comparator=0;
		Integer tempInteger;
		boolean countGreater7=true;
		
		//initialize arrayResults
		while(currResult<7 && countGreater7){
			if(fileWeight[currIndex]==0)
				currIndex++;
			else
			{
				tempInteger = new Integer(currIndex);
				Results.add(tempInteger);
				currResult++;
				currIndex++;				
				
			}
			if(currIndex == fileWeight.length)
				countGreater7 = false;
		}	
		
		sortResults();
		
		if(countGreater7)
		{
			while(currIndex<fileWeight.length){
				tempInteger = (Integer)Results.get(6);
				comparator = fileWeight[tempInteger.intValue()];
				if(fileWeight[currIndex] > comparator){
					tempInteger = new Integer(currIndex); 
					Results.set(6, tempInteger);
					sortResults();
				}
				currIndex++;
			}
			
		}
	}//end setResults()
	
	private void sortResults()
	{
		boolean hasSwapped = true;
		Integer holder;
		int i,compare1,compare2;
		
		while(hasSwapped){
			
			hasSwapped = false;
			for(i=0;i< Results.size()-1;i++){
				
				holder = (Integer)Results.get(i);
				compare1 = holder.intValue();
				holder = (Integer)Results.get(i+1);
				compare2 = holder.intValue();
				if(fileWeight[compare1] < fileWeight[compare2]){
					
					Results.set(i+1, (Integer)Results.get(i));
					Results.set(i, holder);
					hasSwapped=true;
				}//end if x > 0
			}//end for loop
		}//end while
		
	}//end sortResults()

	public String[] getFiles(){
		return files;
	}//end getResults()
}
